<template>
  <div class="diary-manager">
    <!-- 头部标题 -->
    <div class="header">
      <h2>日记信息管理</h2>
    </div>

    <!-- 日记列表 -->
    <el-table
        :data="diaries"
        style="width: 100%"
        border
        stripe
        empty-text="暂无日记记录"
        :default-sort="{ prop: 'date', order: 'descending' }"
    >
      <!-- 日期列 -->
      <el-table-column
          prop="date"
          label="日期"
          width="180"
          sortable
      ></el-table-column>

      <!-- 标题列 -->
      <el-table-column
          prop="title"
          label="标题"
          width="180"
      ></el-table-column>

      <!-- 内容列 -->
      <el-table-column
          prop="content"
          label="内容"
      ></el-table-column>

      <!-- 操作列：编辑、删除 -->
      <el-table-column
          label="操作"
          width="180"
      >
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="editDiary(scope.row)">编辑</el-button>
          <el-button type="text" size="small" @click="deleteDiary(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加新日记按钮 -->
    <div class="add-button">
      <el-button type="primary" @click="showAddDiaryDialog">添加新日记</el-button>
    </div>

    <!-- 添加新日记对话框 -->
    <el-dialog
        :visible.sync="showAddDialog"
        title="添加新日记"
        width="60%"
        @close="hideAddDiaryDialog"
    >
      <el-form :model="newDiary" :rules="rules">
        <!-- 日期 -->
        <el-form-item label="日期" prop="date">
          <el-date-picker v-model="newDiary.date" type="date"></el-date-picker>
        </el-form-item>

        <!-- 标题 -->
        <el-form-item label="标题" prop="title">
          <el-input v-model="newDiary.title"></el-input>
        </el-form-item>

        <!-- 内容 -->
        <el-form-item label="内容" prop="content">
          <el-input type="textarea" v-model="newDiary.content"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="hideAddDiaryDialog">取消</el-button>
        <el-button type="primary" @click="addDiary">添加</el-button>
      </span>
    </el-dialog>

    <!-- 编辑日记对话框 -->
    <el-dialog
        :visible.sync="showEditDialog"
        title="编辑日记"
        width="60%"
        @close="hideEditDiaryDialog"
    >
      <el-form :model="editDiaryData" :rules="rules">
        <!-- 日期 -->
        <el-form-item label="日期" prop="date">
          <el-date-picker v-model="editDiaryData.date" type="date"></el-date-picker>
        </el-form-item>

        <!-- 标题 -->
        <el-form-item label="标题" prop="title">
          <el-input v-model="editDiaryData.title"></el-input>
        </el-form-item>

        <!-- 内容 -->
        <el-form-item label="内容" prop="content">
          <el-input type="textarea" v-model="editDiaryData.content"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="hideEditDiaryDialog">取消</el-button>
        <el-button type="primary" @click="updateDiary">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from '../axios/index'; // 导入 Axios
export default {
  name: 'diary-manager',
  data() {
    return {
      diaries: [], // 存储日记信息的数组
      showAddDialog: false, // 控制是否显示添加对话框
      showEditDialog: false, // 控制是否显示编辑对话框
      newDiary: { // 新日记的初始值
        date: '',
        title: '',
        content: ''
      },
      editDiaryData: { // 编辑日记的数据
        id: null,
        date: '',
        title: '',
        content: ''
      },
      rules: { // 表单验证规则
        date: [
          { required: true, message: '请选择日期', trigger: 'change' }
        ],
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入内容', trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    // 编辑日记
    editDiary(diary) {
      this.editDiaryData = { ...diary }; // 使用深拷贝以避免直接修改原始数据
      this.showEditDialog = true;
    },
    // 保存编辑后的日记
    updateDiary() {
      const { id, date, title, content } = this.editDiaryData;

      // 更新日记数据
      axios.put(`/diaries/${id}`, { date: new Date(date).toISOString().split('T')[0], title, content })
          .then(response => {
            // 在前端更新日记列表中的对应日记数据
            const index = this.diaries.findIndex(diary => diary.id === id);
            if (index !== -1) {
              this.diaries[index] = { id, date, title, content };
            }

            this.showEditDialog = false;
          })
          .catch(error => {
            console.error('更新日记失败:', error);
          });

    },
    // 删除日记
    deleteDiary(diary) {
      axios.delete(`/diaries/${diary.id}`)
          .then(response => {
            const index = this.diaries.indexOf(diary);
            if (index !== -1) {
              this.diaries.splice(index, 1);
            }
          })
          .catch(error => {
            console.error('删除日记失败:', error);
          });
    },
    // 添加新日记
    addDiary() {
      // 转换日期格式为 YYYY-MM-DD
      this.newDiary.date = new Date(this.newDiary.date).toISOString().split('T')[0];

      // 向后端发送添加请求，然后将新日记的数据添加到前端的 diaries 数组中
      axios.post('/diaries', this.newDiary)
          .then(response => {
            this.diaries.push(response.data);
            this.newDiary = { date: '', title: '', content: '' };
            this.showAddDialog = false;
          })
          .catch(error => {
            console.error('添加新日记失败:', error);
          });
    },
    // 隐藏添加日记对话框
    hideAddDiaryDialog() {
      this.showAddDialog = false;
    },
    // 显示添加日记对话框
    showAddDiaryDialog() {
      this.showAddDialog = true;
    },
    // 隐藏编辑日记对话框
    hideEditDiaryDialog() {
      this.showEditDialog = false;
    },
  },
  created() {
    // 获取日记列表数据
    axios.get('/diaries')
        .then(response => {
          // 请求成功后，将获取到的数据存储到 diaries 数组中
          this.diaries = response.data;
        })
        .catch(error => {
          console.error('获取日记列表失败:', error);
        });
  },
}
</script>

<style scoped>
.diary-manager {
  padding: 20px;
}

.header {
  text-align: center;
  margin-bottom: 20px;
}

.add-button {
  text-align: right;
  margin-top: 20px;
}
</style>
